package cn.javadog.smartbreeding.record.service.impl;

import java.util.List;

import cn.javadog.smartbreeding.core.service.BillService;
import cn.javadog.smartbreeding.record.constants.PayStatus;
import cn.javadog.smartbreeding.record.converter.BillConverter;
import cn.javadog.smartbreeding.record.converter.CageGroupConverter;
import cn.javadog.smartbreeding.core.dto.BillDTO;
import cn.javadog.smartbreeding.core.dto.BillDTO.CageGroupDTO;
import cn.javadog.smartbreeding.record.entity.Bill;
import cn.javadog.smartbreeding.record.entity.CageGroup;
import cn.javadog.smartbreeding.record.mapper.BillMapper;
import cn.javadog.smartbreeding.record.mapper.CageGroupMapper;
import cn.javadog.smartbreeding.record.util.SerialNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 余勇
 */
@Service
@com.alibaba.dubbo.config.annotation.Service
public class BillServiceImpl implements BillService {

	@Autowired
	private BillMapper mapper;
	@Autowired
	private BillConverter converter;
	@Autowired
	private CageGroupMapper cageGroupMapper;
	@Autowired
	private CageGroupConverter cageGroupConverter;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String save(BillDTO dto) {
		String billSerialNo = SerialNoUtil.newBillSerialNo(dto.getSaleChannel(), dto.getSaleDate());

		Bill bill = converter.dto2entity(dto);
		bill.setSerialNo(billSerialNo);
		bill.setTotalPrice(compute(dto));
		bill.setPayStatus(PayStatus.UNPAID);
		mapper.insert(bill);

		List<CageGroupDTO> cageGroupDTOs = dto.getCageGroups();
		List<CageGroup> cageGroups = cageGroupConverter.dto2entity(cageGroupDTOs);
		for (CageGroup cageGroup : cageGroups) {
			cageGroup.setBillSerialNo(billSerialNo);
			cageGroupMapper.insert(cageGroup);
		}
		return billSerialNo;
	}

	@Override
	public int compute(BillDTO dto) {
		// 总重 = 所有鸡笼毛重 - 样本笼重/样本笼数 * 总笼数 - 死鸡重
		int cageGroupWeights = dto.getCageGroups()
			.stream()
			.mapToInt(CageGroupDTO::getChickenWeight)
			.sum();
		int cageGroupNum = dto.getCageGroups()
			.stream()
			.mapToInt(CageGroupDTO::getCageNum)
			.sum();
		int totalWeight = cageGroupWeights
			- dto.getSampleCageWeight() / dto.getSampleCageNum() * cageGroupNum
			- dto.getSickChickenWeight();

		return totalWeight * dto.getUnitPrice() / 100;
	}

}
